<!--
 * @Author: 冯本桥
 * @Date: 2025-02-13 13:56:01
 * @LastEditTime: 2025-03-07 14:19:00
 * @LastEditors: 冯本桥
 * @Description:资源详情
 * @FilePath: \teach_system_fe\src\views\teacherManagement\component\teacherTrainingInfo.vue
-->
<template>
  <div v-loading="loading">
    <el-breadcrumb>
      <el-breadcrumb-item
        :to="{ path: '/teacherManagement/teacherTraining' }"
      >{{ nameS }}</el-breadcrumb-item>
      <el-breadcrumb-item>添加章节</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="content-table cad-box">
      <el-button
        style="margin-bottom: 20px"
        type="primary"
        @click="addTeacher"
      >添加章节</el-button>

      <el-table :data="tableData" style="width: 100%; margin: 30px 0">
        <el-table-column
          v-for="(item, index) in config.teacherTrainingInfoTable"
          :key="index"
          :prop="item.key"
          :label="item.name"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="item.slot">
              <el-tag v-if="scope.row[item.key] !== 0" type="danger">{{
                tableSlotValue(item.options, scope.row[item.key])
              }}</el-tag>
              <el-tag v-else type="success">{{
                tableSlotValue(item.options, scope.row[item.key])
              }}</el-tag>
            </span>
            <span v-else>
              <span v-if="item.url">
                <el-link
                  type="primary"
                  :href="scope.row[item.key]"
                  target="_blank"
                >
                  {{ scope.row[item.key] || "-" }}
                </el-link>
              </span>
              <span v-else>
                {{ scope.row[item.key] || "-" }}
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row.id)">
              编辑
            </el-button>
            <el-button
              style="color: #67c23a"
              type="text"
              size="small"
              @click="info(scope.row.id)"
            >
              详情
            </el-button>

            <el-button
              style="color: #ff5757"
              type="text"
              size="small"
              @click="deleteList(scope.row.id)"
            >
              删除
            </el-button>
            <el-button
              v-if="scope.row.status"
              style="color: #909399"
              type="text"
              size="small"
              @click="shield(scope.row.id, 0)"
            >
              启用
            </el-button>
            <el-button
              v-else
              style="color: #909399"
              type="text"
              size="small"
              @click="shield(scope.row.id, 1)"
            >
              屏蔽
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-sizes="[10, 15, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      :wrapper-closable="false"
      size="50%"
    >
      <div style="padding: 0 20px" class="box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
          :disabled="disabledFrom"
        >
          <el-form-item label="章节名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入章节名称" />
          </el-form-item>
          <el-form-item label="视频信息" prop="videoAddress">
            <el-input
              v-model="ruleForm.videoAddress"
              placeholder="请输入视频链接或在下方上传视频"
            />
          </el-form-item>

          <el-form-item>
            <el-upload
              class="upload-demo"
              action="/api/system/upload"
              multiple
              accept=""
              :limit="1"
              :file-list="fileList"
              :on-preview="openFile"
              :before-upload="beforeVideoUpload"
              :on-success="
                (response, file, fileList) =>
                  handleAvatarSuccess(response, file, fileList, 'videoAddress')
              "
            >
              <el-button
                size="small"
                icon="el-icon-upload2"
              >上传视频</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-input
              v-model="ruleForm.priority"
              type="number"
              placeholder="请输入优先级"
            />
          </el-form-item>
          <div class="flex-box">
            <div class="title-box">小节信息</div>
            <el-button v-if="!disabledFrom" type="text" @click="addInput">{{
              ruleForm.childList.length >= 1 ? "继续添加" : "添加"
            }}</el-button>
          </div>

          <nested-form
            :rule-form="ruleForm.childList"
            :disabled-from="!disabledFrom"
          />
        </el-form>
        <div
          v-if="!disabledFrom"
          style="
            margin-top: 50px;
            float: right;
            margin-right: 15px;
            padding-bottom: 30px;
          "
        >
          <el-button type="primary" @click="drawerAdd">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import * as config from '../config'
import {
  getPerformanceList,
  addChapter,
  courseInfo,
  courseDelete,
  courseState
} from '../api/teacherTraining'
import NestedForm from './NestedForm.vue'
export default {
  components: {
    NestedForm
  },
  data () {
    return {
      config: config,
      drawer: false,
      loading: false,
      disabledFrom: false,
      ruleForm: {
        childList: [],
        type: 1,
        name: '',
        videoAddress: ''
      },
      fileList: [],
      rules: {
        name: [{ required: true, message: '请输入章节名称', trigger: 'blur' }]
      },
      drawerTitle: '',
      videoAccept: 'video/mp4, video/webm, video/ogg', // 支持的视频格式
      tableData: [],
      pagination: {
        pageNum: 0,
        pageSize: 10
      },
      total: 0,
      ids: '',
      nameS: ''
    }
  },
  computed: {
    tableSlotValue () {
      return (data, value) => {
        return data.find((item) => item.value * 1 === value * 1)?.label || ''
      }
    },
    getFileList () {
      return (value) => {
        const urlArray = value?.split(',').filter((url) => url.trim() !== '')
        return urlArray?.map((url) => ({ url: url.trim(), name: url.trim() }))
      }
    }
  },
  created () {
    const { id, name } = this.$route.query
    this.ids = id
    this.nameS = name
    this.getTableList()
  },
  mounted () {},
  methods: {
    async getTableList () {
      this.loading = true
      try {
        const siz = JSON.parse(JSON.stringify(this.pagination.pageNum))
        const res = await getPerformanceList({
          courseId: this.ids,
          ...this.pagination,
          pageNum: siz ? siz - 1 : siz
        })
        this.tableData = res.content
        this.total = res.totalElements
        console.log(res)
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    async addTableList () {
      try {
        const list = Object.assign({ courseId: this.ids }, this.ruleForm)
        list.priority = this.ruleForm.priority * 1
        await addChapter(list)
        this.$message({
          type: 'success',
          message: '成功'
        })
        this.beforeClose()
        this.getTableList()
      } catch (error) {
        console.log(error)
      }
    },

    openFile (file) {
      window.open(file.url)
    },

    beforeVideoUpload (file) {
      // 可以加入一些上传前的检查，检查是否为视频文件
      const isVideo = file.type.startsWith('video/')
      if (!isVideo) {
        this.$message.error('请上传视频文件')
      }
      return isVideo
    },

    addTeacher () {
      console.log('添加章节')
      this.disabledFrom = false
      this.drawerTitle = '添加章节'
      this.drawer = true
    },

    info (id) {
      console.log('详情')
      this.disabledFrom = true
      this.drawerTitle = '详情'
      this.drawer = true
      this.getInfoList(id)
    },

    async getInfoList (id) {
      try {
        const res = await courseInfo({ id: id })
        this.ruleForm = res
        this.fileList = this.getFileList(res.videoAddress) || ''
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },

    edit (id) {
      this.disabledFrom = false
      this.drawerTitle = '编辑'
      this.drawer = true
      this.getInfoList(id)
    },

    deleteList (id) {
      console.log('删除')
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteListDate(id)
        })
        .catch(() => {})
    },

    shield (id, value) {
      console.log('屏蔽')
      this.$confirm('是否确认屏蔽?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.updataState(id, value)
        })
        .catch(() => {})
    },

    async updataState (id, value) {
      try {
        await courseState({ id: id, status: value })
        this.$message({
          type: 'success',
          message: '屏蔽成功!'
        })
        this.getTableList()
      } catch (error) {
        console.log(error)
      }
    },

    beforeClose () {
      try {
        this.$refs.ruleForm.resetFields()
        this.ruleForm = {
          childList: [],
          type: 1,
          name: '',
          videoAddress: ''
        }
        this.fileList = []
      } catch (error) {
        console.log(error)
      }
      this.ruleForm.childList = []
      this.drawer = false
    },

    addInput () {
      this.ruleForm.childList.push({
        name: '',
        videoAddress: ''
      })
    },

    async deleteListDate (id) {
      try {
        await courseDelete({ id: id })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getTableList()
      } catch (error) {
        console.log(error)
      }
    },

    drawerAdd () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log(this.ruleForm, 'a')
          this.addTableList()
          // alert("submit!");
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getTableList()
    },

    handleCurrentChange (val) {
      this.pagination.pageNum = val
      this.getTableList()
    },

    handleAvatarSuccess (response, file, fileList, key) {
      const a = []
      fileList.forEach((element) => {
        if (
          element.response &&
          element.response?.data &&
          element.response?.data.url
        ) {
          a.push(element.response.data.url)
        }
      })
      this.ruleForm[key] =
        this.ruleForm[key] && this.ruleForm[key].trim() !== ''
          ? this.ruleForm[key] + ',' + a.join(',')
          : a.join(',')
    }
  }
}
</script>

<style scoped lang="scss">
.box-card {
  padding: 30px 30px;
  background-color: white;
}

.content-table {
  margin-top: 30px;
}

.flex-box {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title-box {
    font-weight: bold;
    font-size: 20px;
  }
}

.input-item-box {
  padding: 20px 20px;
  background-color: #fafafc;
  border: 1px solid #ebebee;
  border-radius: 5px;
  margin-top: 20px;
}
</style>
